#include <mysql/mysql.h>
#include <iostream>
using namespace std;
#include <unistd.h>
#include <string>

const string host = "localhost";
const string user = "mian_yang";
const string passwd = "111111";
const string db = "mian_yang_25_5_4";
const int port = 3306;

int main()
{
    MYSQL *sql = mysql_init(nullptr);
    if (sql == nullptr) 
    {
        cerr << "create mysql handle error" << endl;
        return -1;
    }

    if (mysql_real_connect(sql, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0) < 0)
    {
        cerr << "connect error" << endl;
        return 0;    
    }

    cout << "connect success" << endl;

    string sl;
    // while (true)
    // {
    //     if (!getline(cin, sl) || sl == "quit") break;
    //     int ret = mysql_query(sql, sl.c_str());
    //     if (ret == 0)
    //     {
    //         cout << "Query OK!" << endl;
    //     }
    //     else 
    //     {
    //         cerr << "Error !" << endl;
    //     }
    // }

    getline(cin, sl);
    int ret = mysql_query(sql, sl.c_str());
    if (ret == 0) 
    {
        cout << "Query OK!" << endl;
    }
    else
    {
        cerr << "Error !" << endl;
    }

    MYSQL_RES *res = mysql_store_result(sql);
    uint64_t cols = mysql_num_fields(res);
    MYSQL_FIELD *fields = mysql_fetch_fields(res);
    for (int i = 0; i < cols; i++)
    {
        cout << fields[i].name << "\t";
    }
    cout << endl;
    uint64_t rows = mysql_num_rows(res);
    for (int i = 0; i < rows; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for (int i = 0; i < cols; i++)
        {
            cout << row[i] << "\t";
        }
        cout << endl;
    }

    mysql_close(sql);
    return 0;
}